package com.sali.DP;

/**
 * 在一个由 '0' 和 '1' 组成的二维矩阵内，找到只包含 '1' 的最大正方形，并返回其面积。
 */
public class LeetCode_221 {


    public int maximalSquare(char[][] matrix) {
        int row = matrix.length;
        int col = matrix[0].length;


        int[][] dp = new int[row][col];

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (i == 0) {
                    if (matrix[i][j] == '1') {
                        dp[i][j] = 1;
                    }
                    continue;
                }
                if (matrix[i][j] != '1') {
                    continue;
                }
                dp[i][j] = dp[i - 1][j] + 1;
            }
        }

        int maxSize = 0;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (dp[i][j] == 0) {
                    continue;
                }
                int curHeight = dp[i][j];
                for (int k = j; k >= 0; k--) {
                    if (dp[i][k] == 0) {
                        break;
                    }
                    curHeight = Math.min(curHeight, dp[i][k]);
                    int curWeight = j - k + 1;
                    maxSize = Math.max(maxSize, Math.min(curHeight, curWeight));
                }
            }
        }

        return maxSize * maxSize;
    }

}
